package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {

    @Autowired
    private AliOSSProperties aliOSSProperties;

    public String upload(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString() + extname;
        String accessKeyId = aliOSSProperties.getACCESSKEYID();
        String accessKeySecret = aliOSSProperties.getACCESSKEYSECRET();
        String bucketName = aliOSSProperties.getBUCKETNAME();
        String endpoint = aliOSSProperties.getENDPOINT();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        ossClient.putObject(bucketName, filename, inputStream);
        String url = endpoint.split("//")[0] + "//"  + bucketName + "." + endpoint.split("//")[1] +"/" + filename;
        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}
